#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

class tcpClient
{
public:
    tcpClient(const std::string &serverip, const uint16_t &serverport)
        : _sock(-1), _serverip(serverip), _serverport(serverport)
    {
    }

    void initClient()
    {
        // 1. 创建socket
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(FATAL, "create socket error");
            exit(2);
        }
    }
    void start()
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);

        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());

        int n = connect(_sock, (struct sockaddr *)&server, sizeof server);
        if (n < 0)
        {
            logMessage(ERROR, "connect error");
        }
        else
        {
            std::string message;
            while (true)
            {
                std::cout << "Please Enter#";
                getline(std::cin, message);
                write(_sock, message.c_str(), message.size());

                char buffer[1024];
                int n = read(_sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    std::cout << "server 回显# " << buffer << std::endl;
                }
                else
                    break;
            }
        }
    }
    ~tcpClient()
    {
        if (_sock > 0)
            close(_sock);
    }

private:
    int _sock;
    std::string _serverip;
    uint16_t _serverport;
};
